<template>
  <div style="width:100%;">
    <div class="editorBox">
      <QuillEditor id="editorId" ref="myQuillEditor" v-model:content="editorContent" contentType="html"
        :options="options" />
    </div>
    <!-- 上传图片 -->
    <el-upload action="string" :show-file-list="false" :http-request="requestUploadImage"
      :before-upload="handleBeforeUploadImage" :on-error="handleUploadError" class="editor-img-uploader">
      <i ref="uploadImageRef" class="Plus editor-img-uploader"></i>
    </el-upload>
    <!-- 上传视频弹窗 -->
    <Model title="置入视频" :modelShow="modelShow" width="50" @cancel="Cancel" @confirm="Confirm">
      <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="82px" status-icon>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="视频链接" prop="url" style="margin-bottom:18px;">
              <el-input type="input" v-model="ruleForm.url" placeholder="请输入视频链接"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传视频" prop="fileUrl">
              <div class="uploadList">
                <div class="items"  v-if="ruleForm.fileUrl">
                  <video :src='ruleForm.fileUrl' style="width: 100%;height: 100%;object-fit: cover;"></video>
                  <transition name="fade" mode="out-in">
                    <div class="model-img-box" @click="playVideo">
                      <div class="mine-flex-box">
                        <svg class="icon svg-icon" aria-hidden="true" style="width: 24px;height: 24px;">
                          <use xlink:href="#icon-bofang"></use>
                        </svg>
                      </div>
                    </div>
                  </transition>
                  <el-icon @click="handleRemove"><CircleCloseFilled /></el-icon>
                </div>
                <div v-else style="display: inline-block;height: 88px">
                  <el-upload class="avatar-uploader" :show-file-list="false" :http-request="requestUploadVideo"
                    :before-upload="handleBeforeUploadVideo">
                    <el-icon class="avatar-uploader-icon">
                      <Plus />
                    </el-icon>
                    <div>点击上传视频</div>
                  </el-upload>
                  <!-- 进度条 -->
                  <div class="progressBox" v-if="isShowProgress">
                    <el-progress :stroke-width="8" style="height:88px;height:88px;" type="circle"
                      :percentage="progressNum" />
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </Model>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { QuillEditor, Quill } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css';
// import { getToken } from "@/utils/auth";
import { getCurrentInstance, reactive, ref, toRaw, computed } from "vue";
import upload from '../../util/OSSUpload'
import uploadBig from '../../util/OSSUploadBig'
import Video from "@/util/QuillVideo.js";
import Model from './Model.vue'
Quill.register({ 'formats/video': Video }, true);
const { proxy } = getCurrentInstance();
const emit = defineEmits(['update:content', 'getFileId'])
const props = defineProps({
  /* 编辑器的内容 */
  content: {
    type: String,
    default: '',
  },
  /* 只读 */
  readOnly: {
    type: Boolean,
    default: false,
  },
  // 上传文件大小限制(MB)
  fileSize: {
    type: Number,
    default: 5,
  },
  // maxSize: {
  //   type: Number,
  //   default: 200,
  // },
  /* 类型（base64格式、url格式） */
  type: {
    type: String,
    default: 'url',
  },
})
const myQuillEditor = ref()
const editorContent = computed({
  get: () => props.content,
  set: (val) => {
    console.log(val)
    emit('update:content', val)
  }
});
// 上传视频弹窗数据
const modelShow = ref(false)
const ruleForm = ref({
  url: '',
  fileUrl: ''
})
// 上传视频前校检格式和大小
const isShowProgress = ref(false)
const progressNum = ref(0)
function handleBeforeUploadVideo(file) {
  let acceptArr = ['video/mp4']
  const isVideo = acceptArr.includes(file.type)
  const isLt1M = file.size / 1024 / 1024 < props.maxSize
  if (!isVideo) {
    this.hideLoading()
    this.$message.error('只能上传mp4格式文件!')
  }
  // if (!isLt1M) {
  //   this.hideLoading()
  //   this.$message.error(`上传文件大小不能超过 ${props.maxSize}MB!`)
  // }
  if (isVideo) {
    isShowProgress.value = true
  }
  return isVideo
}
function requestUploadVideo(options) {
  uploadBig(options.file, (res) => {
    ruleForm.value.fileUrl = res.inch
    isShowProgress.value = false
  },
    (error) => {
      isShowProgress.value = false
      ElMessage.error('视频上传失败')
    },
    (percent) => {
      progressNum.value = percent.percent
    }
  )
}
// 点击确定批量插入视频
function insertVideo(url) {
  // 获取富文本实例
  let quill = toRaw(myQuillEditor.value).getQuill();
  // 获取光标位置
  let length = quill.selection.savedRange.index;
  // 插入图片，res为服务器返回的图片链接地址
  quill.insertEmbed(length, "video", url);
  // 调整光标到最后
  quill.setSelection(length + 1);
  emit('getFileId', url)
}
function Confirm() {
  if (!ruleForm.value.url && !ruleForm.value.fileUrl) {
    return ElMessage.error('请上传视频')
  }
  if (ruleForm.value.url) {
    insertVideo(ruleForm.value.url)
  }
  if (ruleForm.value.fileUrl) {
    insertVideo(ruleForm.value.fileUrl)
  }
  modelShow.value = false
}
function Cancel() {
  modelShow.value = false
  ruleForm.value.url = ''
  ruleForm.value.fileUrl = ''
}
// 富文本相关配置
const options = reactive({
  theme: 'snow',
  debug: 'warn',
  modules: {
    // 工具栏配置
    toolbar: {
      container: [
        [
          "bold", "italic", "underline", "link", "image", "video",
          { color: [] },
          { background: [] },
          { align: [] },
        ]
      ],
      handlers: {
        // 重写图片上传事件
        image: function (value) {
          if (value) {
            //调用图片上传
            proxy.$refs.uploadImageRef.click()
          } else {
            Quill.format("image", true);
          }
        },
        // 重写视频上传事件
        video: function (value) {
          if (value) {
            //调用图片上传
            modelShow.value = true
            // proxy.$refs.uploadVideoRef.click()
          } else {
            Quill.format("video", true);
          }
        },
      },
    }
  },
  placeholder: '请输入内容',
  readOnly: props.readOnly,
})

// 上传图片前校检格式和大小
function handleBeforeUploadImage(file) {
  const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
  const isJPG = type.includes(file.type);
  //检验文件格式
  if (!isJPG) {
    ElMessage.error('图片格式错误!')
    return false
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      ElMessage.error(`上传文件大小不能超过 ${props.fileSize} MB!`)
      return false
    }
  }
  return true
}
function requestUploadImage(options) {
  upload(options.file,(res) => {
    console.log(res)
    // 获取富文本实例
    let quill = toRaw(myQuillEditor.value).getQuill();
    // 获取光标位置
    let length = quill.selection.savedRange.index;
    // 插入图片，res为服务器返回的图片链接地址
    let imageUrl = res.inch
    quill.insertEmbed(length, "image", imageUrl);
    // 调整光标到最后
    quill.setSelection(length + 1);
    emit('getFileId', res.inch)
  },
    (error) => {
      console.log(error)
      ElMessage.error('图片插入失败')
    },
    (percent) => {
      console.log(percent)
    }
  )
}
// 上传失败处理
function handleUploadError() {
  ElMessage.error('图片插入失败')
}
const handleRemove = () => {
  ruleForm.value.fileUrl = ''
}
const playVideo = () => {
  // 获取富文本实例
  window.open(ruleForm.value.fileUrl,'_blank')
}
defineExpose({ myQuillEditor })
</script>
<style>
.editorBox {
  height: calc(100% - 20px);
}

.ql-toolbar {
  width: 100%;
  white-space: pre-wrap !important;
  line-height: normal !important;
}

.editor-img-uploader {
  display: none;
}

.ql-editor {
  min-height: 200px;
  color: #000000;
}

.ql-editor img {
  width: 100%;
  display: inline-block;
}

.ql-editor video {
  width: 100%;
  display: inline-block;
}

.ql-toolbar.ql-snow+.ql-container.ql-snow {
  max-height: 90%;
}

.ql-snow .ql-tooltip[data-mode='link']::before {
  content: '请输入链接地址:';
}

.ql-snow .ql-tooltip.ql-editing a.ql-action::after {
  border-right: 0px;
  content: '保存';
  padding-right: 0px;
}

.ql-snow .ql-tooltip[data-mode='video']::before {
  content: '请输入视频地址:';
}

.ql-snow .ql-picker.ql-size {
  width: 60px;
}

.ql-snow .ql-picker.ql-header {
  width: 70px;
}

.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: '14px';
}

.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='small']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='small']::before {
  content: '12px';
}

.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='large']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='large']::before {
  content: '18px';
}

.ql-snow .ql-picker.ql-size .ql-picker-label[data-value='huge']::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value='huge']::before {
  content: '32px';
}

.ql-snow .ql-picker.ql-header .ql-picker-label::before,
.ql-snow .ql-picker.ql-header .ql-picker-item::before {
  content: '文本';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='1']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='1']::before {
  content: '标题1';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='2']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='2']::before {
  content: '标题2';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='3']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='3']::before {
  content: '标题3';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='4']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='4']::before {
  content: '标题4';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='5']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='5']::before {
  content: '标题5';
}

.ql-snow .ql-picker.ql-header .ql-picker-label[data-value='6']::before,
.ql-snow .ql-picker.ql-header .ql-picker-item[data-value='6']::before {
  content: '标题6';
}

.ql-snow .ql-picker.ql-font .ql-picker-label::before,
.ql-snow .ql-picker.ql-font .ql-picker-item::before {
  content: '标准字体';
}

.ql-snow .ql-picker.ql-font .ql-picker-label[data-value='serif']::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value='serif']::before {
  content: '衬线字体';
}

.ql-snow .ql-picker.ql-font .ql-picker-label[data-value='monospace']::before,
.ql-snow .ql-picker.ql-font .ql-picker-item[data-value='monospace']::before {
  content: '等宽字体';
}
</style>
<style lang="scss" scoped>
.uploadList {
  display: flex;
  flex-flow: wrap;
  width: 140px;
  height: 88px;
  margin-bottom: 30px;
  position: relative;

  .progressBox {
    position: absolute;
    width: 140px;
    height: 88px;
    top: 0px;
    left: 0px;
    right: 0px;
    bottom: 0px;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;

    :deep(.el-progress){
      height: 60px!important;
      width: 60px!important;
    }
    :deep(.el-progress-circle) {
      height: 60px !important;
      width: 60px !important;
    }
    :deep(.el-progress--circle .el-progress__text){
        color: #ffffff;
    }
  }
  .items {
    width: 140px;
    height: 88px;
    background: #EEEEEE;
    display: inline-block;
    margin: 0 20px 0 0;
    border-radius: 4px;
    border: 1px dashed #DCDCDC;
    position: relative;
    padding: 6px;
    box-sizing: border-box;
    margin-bottom: 20px;
    position: relative;
    .el-icon{
        position: absolute;
        top: -8px;
        right: -8px;
        font-size: 18px;
        color:#B52427;
        z-index: 9999;
        cursor: pointer;
    }
    .el-image {
      border-radius: 4px;
      background: #ffffff
    }

    .model-img-box {
      background: rgba(0, 0, 0, 0.3);
      width: 100%;
      height: 88px;
      position: absolute;
      cursor: pointer;
      top: 0;
      left: 0;
      border-radius: 4px;
      z-index: 9;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;

      i {
        color: #fff;
        font-size: 16px;
      }

      .mine-flex-box {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .el-icon {
          transition: all 1s;
          font-weight: bold;
        }

        span {
          width: 1px;
          margin: 0 7px;
          height: 12px;
          background: rgba(255, 255, 255, 0.9);
          display: inline-block;
        }

        .el-icon:first-of-type:hover {
          transform: scale(1.2);
        }

        .el-icon:last-of-type:hover {
          transform: scale(1.2);
        }

        :deep(.avatar-uploader) {
          width: 16px;
          height: 16px;
          margin: 0px;


        }

        :deep(.avatar-uploader .el-upload) {
          width: 16px;
          height: 16px;
          border: none;
          background-color: transparent;
        }
      }

      .zoom-big-box {
        display: flex;
        align-items: center;
        transition: all 1s;
      }
    }
  }
}

:deep(.avatar-uploader .el-upload) {
  width: 140px;
  height: 88px;
  background: #EEEEEE;
  border-radius: 4px;
  border: 1px dashed #DCDCDC;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.4);
  box-sizing: border-box;
}

:deep(.el-icon.avatar-uploader-icon) {
  color: #000000;
  margin-bottom: 3px;
  font-size: 14px;
  font-weight: 600;
}

:deep(.avatar-uploader) {
  margin: 0px;
  width: 140px;
  height: 88px;
}

:deep(.el-progress--circle) {
  align-items: center !important;
  display: inline-flex!important;
}
</style>